import React, { useEffect, useState } from 'react';
import { Form, Input, Button, message } from 'antd';
import type { FormProps } from 'antd';
import { useNavigate } from 'react-router-dom';
import { useRequest } from 'ahooks';

import { IUserLogin, getUserService, userRegisterService } from '../../api/common';

const Register = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [users, setUsers] = useState<Array<IUserLogin>>([]);

  const { loading, data } = useRequest(async () => {
    const res = await getUserService();
    return res;
  });

  const onFinish: FormProps<IUserLogin>['onFinish'] = async (values) => {
    const { username, password } = values;
    const user = users.find((item) => item.username === username);
    if (!user) {
      const { data } = await userRegisterService({ username, password });
      if (data) {
        message.success('注册成功');
      }
    } else {
      message.error('该账户已存在，请重新注册');
    }
  };

  useEffect(() => {
    if (!loading) {
      setUsers(data?.data);
    }
  }, [loading]);

  return (
    <div className="w-full h-full flex justify-center items-center bg-blue-300">
      <div className="w-2/6 h-3/6 bg-white rounded-lg flex flex-col">
        <h3 className="py-5 text-center border-b-red-400">注册</h3>
        <div className="flex-1 px-10 py-10">
          <Form
            form={form}
            onFinish={onFinish}
            autoComplete="off"
            labelAlign="left"
            labelCol={{ span: 6 }}
          >
            <Form.Item<IUserLogin>
              label="用户名"
              name="username"
              rules={[
                {
                  validator: (_, value) => {
                    if (!/^\S+@\S+\.\S+$/.test(value) && !/^[\+]?[\d]{9,15}$/.test(value)) {
                      return Promise.reject(new Error('请输入有效的手机号或邮箱'));
                    }
                    return Promise.resolve();
                  }
                }
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item<IUserLogin>
              label="密码"
              name="password"
              rules={[{ required: true, message: '请输入密码!' }]}
            >
              <Input.Password />
            </Form.Item>

            <Form.Item<IUserLogin>
              label="确认密码"
              name="confirmPassword"
              rules={[
                { required: true, message: '请输入密码!' },
                {
                  validator: (_, value) => {
                    if (value !== form.getFieldValue('password')) {
                      return Promise.reject(new Error('两次密码不一致!'));
                    }
                    return Promise.resolve();
                  }
                }
              ]}
            >
              <Input.Password />
            </Form.Item>

            <Form.Item className="text-center">
              <Button className="w-[120px] h-[35px]" type="primary" htmlType="submit">
                注册
              </Button>
            </Form.Item>
          </Form>
        </div>
        <div
          className="px-10 py-10 text-right text-cyan-400 cursor-pointer"
          onClick={() => navigate('/')}
        >
          已有账号，请前去登录
        </div>
      </div>
    </div>
  );
};

export default Register;
